package zzu.xjc.http.util;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;

public class LRUCache<K,V> extends LinkedHashMap<K,V> {
    private final int MaxCacheSize;
    private Consumer<K> keyCallback;
    private Consumer<V> valueCallback;

    public LRUCache(int size, Consumer<K> keyRemoveCallback, Consumer<V> valueRemoveCallback){
        super(size + 1,1,true);
        this.MaxCacheSize = size;
        this.keyCallback = keyRemoveCallback;
        this.valueCallback = valueRemoveCallback;
    }
    public LRUCache(int size){
        super(size + 1,1,true);
        this.MaxCacheSize = size;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        if (size() > MaxCacheSize){
            if (keyCallback != null){
                keyCallback.accept(eldest.getKey());
            }
            if(valueCallback != null){
                valueCallback.accept(eldest.getValue());
            }
            return true;
        }
        return false;
    }

}
